#include <stdlib.h>
#include <GL/glut.h>
#include "Sprite.hpp"
#include "../ResourceManagers/TextureManager.hpp"
#include "../Extensions/ExtensionsLoader.hpp"

using namespace std;

Sprite::Sprite(string name, MVector3D& origin, float fScaleX, float fScaleZ, TexType eTextureType):
m_bToRender(true)
{
	m_name = name;

    m_origin = origin;
	setPosition(origin);
	m_fScaleX = fScaleX;
	m_fScaleZ = fScaleZ;

	m_eTextureType = eTextureType;

	TextureManager::GetInstance()->LoadTexture(m_name, eTextureType);
}

Sprite::~Sprite()
{
	TextureManager::GetInstance()->UnloadTexture(m_name);
}

void Sprite::SetScaleX(float &fScale)
{
	m_fScaleX = fScale;
}

void Sprite::SetScaleZ(float &fScale)
{
	m_fScaleZ = fScale;
}

void Sprite::Translate(MVector3D &translation)
{
	m_translation = m_translation + translation;
}

float& Sprite::GetScaleX()
{
	return m_fScaleX;
}

float& Sprite::GetScaleZ()
{
	return m_fScaleZ;
}

void Sprite::render()
{
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, ((TextureObject*)(TextureManager::GetInstance()->GetTexture(m_name)))->GetTextureID());
	ExtensionsLoader::glActiveTextureARB(GL_TEXTURE0_ARB);

	glBegin(GL_QUADS);

	//! left-top
	glTexCoord2f(0.0, 1.0);
	glVertex3f(m_origin.x - 0.5*m_fScaleX + m_translation.x,
		       m_origin.y + m_translation.y,
			   m_origin.z - 0.5*m_fScaleZ + m_translation.z );

	//! left-bottom
	glTexCoord2f(0.0, 0.0);
	glVertex3f(m_origin.x - 0.5*m_fScaleX + m_translation.x,
		       m_origin.y + m_translation.y,
			   m_origin.z + 0.5*m_fScaleZ + m_translation.z );

	//! right-bottom
	glTexCoord2f(1.0, 0.0);
	glVertex3f(m_origin.x + 0.5*m_fScaleX + m_translation.x,
		       m_origin.y + m_translation.y,
			   m_origin.z + 0.5*m_fScaleZ + m_translation.z );

	//! right-top
	glTexCoord2f(1.0, 1.0);
	glVertex3f(m_origin.x + 0.5*m_fScaleX + m_translation.x,
		       m_origin.y + m_translation.y,
			   m_origin.z - 0.5*m_fScaleZ + m_translation.z );

	glEnd();

	glDisable(GL_TEXTURE_2D);
}

//EOF